//
//  QTicketPhotoView.m
//  QoilPublic
//
//  Created by 杨凯 on 16/12/13.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QTicketPhotoView.h"
#import "HZPhotoBrowser.h"

@interface QTicketPhotoView()<HZPhotoBrowserDelegate>

@end
@implementation QTicketPhotoView

- (void)setArr:(NSArray *)arr{

    _arr = arr;
    NSInteger imageCount = _arr.count;

    while (self.subviews.count < imageCount) { //如果重用cell的containView里面的imageView个数不够，则添加
        UIImageView *imgView = [[UIImageView alloc] init];
        imgView.backgroundColor=[UIColor orangeColor];
        imgView.contentMode=UIViewContentModeScaleAspectFill;
        imgView.clipsToBounds = YES;
        imgView.userInteractionEnabled=YES;
        [self addSubview:imgView];
    }
    
    for (int i=0; i<self.subviews.count; i++) {
        UIImageView *imgView = self.subviews[i];
        if (i < imageCount) {
            [imgView sd_setImageWithURL:[NSURL URLWithString:_arr[i]] placeholderImage:[UIImage imageNamed:@"mainPlace_image"]];
            imgView.tag = i;
            [imgView addGestureRecognizer:[self singleTapGestureRecognizer]];
            imgView.hidden = NO;
        } else { //超出个数的imageView隐藏掉，也不计算它们的frame
            imgView.hidden = YES;
        }
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    NSInteger imageCount = _arr.count;
    CGFloat W = (kScreenWidth-30)/3;
    CGFloat H = W;
    CGFloat spanc = 5;//横间距
    CGFloat hspanc = 5;//纵间距
    int count = (int)_arr.count;
    int rows = (count-1)/3 + 1;
    
    for (int i = 0; i<imageCount; ++i) {
        UIImageView *imgView = self.subviews[i];
        imgView.frame = CGRectMake(i%3*(W+spanc), i/3*(H+hspanc), W, H);
    }
    _viewHeight = rows*(H+hspanc)-hspanc;

}


#pragma mark - private
- (UITapGestureRecognizer*)singleTapGestureRecognizer {
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imgViewTapped:)];
    return tapGesture;
}

#pragma mark - Event
- (void)imgViewTapped:(UITapGestureRecognizer*) tapGestureRecognizer {
    HZPhotoBrowser *browserVc = [[HZPhotoBrowser alloc] init];
    browserVc.sourceImagesContainerView = self; // 原图的父控件
    
    NSArray *imgArr = _arr;
    browserVc.imageCount = imgArr.count; // 图片总数
    browserVc.currentImageIndex = (int)tapGestureRecognizer.view.tag;
    browserVc.delegate = self;
    [browserVc show];
    CLog(@"=====");
}

#pragma mark - photobrowser代理方法
- (UIImage *)photoBrowser:(HZPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index
{
    UIImage *img = [self.subviews[index] image];
    if (!img) {
        return [UIImage imageNamed:@"mainPlace_image"];
    }
    return img;
}

- (NSURL *)photoBrowser:(HZPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index
{
    return [NSURL URLWithString:_arr[index]];
}




@end
